package com.gack.netty.util.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gack.netty.messageModle.testModle;

/** 
* @ClassName: Json2BeanConvertUtil 
* @Description: TODO(使用jackson 将javaBean转化为json字符串 与 json字符串的解析) 
* @author (ZhangXinYu)  
* @date 2018年9月2日 下午11:19:36 
* @version V1.0 
*/
public class Jackson2BeanConvertUtil {
	private static ObjectMapper objectMapper = new ObjectMapper();
	
	/**
	 * Convert JavaBean to String
	 */
	public static String Object2Json(Object object) throws JsonProcessingException {
		return objectMapper.writeValueAsString(object);
	}
	
	/**
	 * parse JsonString to JavaBean
	 */
	public static Object Json2Object(String json, Class<?> objectClass) throws JsonMappingException, JsonParseException, IOException {
		return objectMapper.readValue(json, objectClass);
	}
	
	// test
	public static void main(String[] args) throws Exception{
		testModle testModle1 = new testModle();
		testModle1.setId("110");
		testModle1.setAge(22);
		testModle1.setInfo(new ArrayList<>(Arrays.asList("1","2","3")));
		testModle1.setDate(new Date());
		String jsonStr = Jackson2BeanConvertUtil.Object2Json(testModle1);
		System.out.println(jsonStr);
		testModle testModle2 = (testModle) Jackson2BeanConvertUtil.Json2Object(jsonStr, testModle.class);
		System.out.println(testModle2.getId());
	}
}
